﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace AudioDemo.View
{
    /// <summary>
    /// text4.xaml 的交互逻辑
    /// </summary>
    public partial class text4 : Window
    {
        public text4()
        {
            InitializeComponent();

            richTextBox.Document = doc;
            richTextBox.FontSize = 20;
            //添加内容
            appendLine(null, "从你的全世界路过");
            appendLine("one", "海上生明月");
            appendLine(null, "从你的全世界路过");
            appendLine(null, "天涯共此时");
            appendLine("two", "张三丰");
            appendLine(null, "从你的全世界路过");
            appendLine(null, "鲁迅先生");
            appendLine(null, null);

        }
        FlowDocument doc = new FlowDocument();
        private void appendLine(string name, string line)
        {
            Paragraph p = new Paragraph();
            if (string.IsNullOrEmpty(name) == false)
                doc.RegisterName(name, p);
            Run r = new Run(line);
            p.TextAlignment = TextAlignment.Center;
            p.Inlines.Add(r);
            doc.Blocks.Add(p);
        }
        int pIndex = 0;
        double curTop = 0;
        private void button_Click(object sender, RoutedEventArgs e)
        {
            //定时控制内容显示和滚动条位置
            DispatcherTimer _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromSeconds(1);
            _timer.Tick += (st, et) =>
            {
                //获取指定行的内容
                BlockCollection col = richTextBox.Document.Blocks;
                int index = 0;
                TextElement prev = null;
                foreach (TextElement item in col)
                {
                    //修改当前行的样式
                    if (index == pIndex)
                    {
                        AlterStyle(item, prev);
                    }
                    index++;
                    prev = item;
                }
                pIndex++;
            };
            _timer.Start();
        }
        private void AlterStyle(TextElement item, TextElement prev)
        {
            //当前行
            Paragraph cP = item as Paragraph;
            cP.Foreground = Brushes.Red;
            TextRange range = new TextRange(cP.ContentStart, cP.ContentEnd);
            //滚动位置控制
            if (pIndex > 0 && range.Text.Length > 0)
            {
                //上一行，样式回调
                if (prev != null)
                {
                    prev.Foreground = Brushes.Black;
                }
                curTop += range.Text.Length > 7 ? 40 : 20;
                curTop += 20;
                richTextBox.ScrollToVerticalOffset(curTop);
            }
        }
    }
}
